//
//  ZJVidoViewController.m
//  ZhongWangYuanApp
//
//  Created by ZJ on 2018/6/2.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "ZJVidoViewController.h"
#import "PLVVodSkinPlayerController.h"
#import "ZJCourseNameView.h"
#import "ZJCourseIntroView.h"
#import "ZJCourseTeacherView.h"
#import "ZJCourseCommentAndCollectView.h"
#import "ZJCourseSelectionsView.h"
#import "ZJSelectionsMdel.h"
#import "ZJCourseTeacherModel.h"
#import "AppDelegate.h"
#import "YBCommentVideoView.h"
#import "KYVedioPlayer.h"
@interface ZJVidoViewController ()<ZJCourseCommentAndCollectViewDelegate,ZJCourseSelectionsViewDelegate,ZJCourseNameViewDelegate,ZJVideoCoverViewDelegate,YBCommentVideoViewDelegate,KYVedioPlayerDelegate>
{
    BOOL _isComment;/**< 是否评价 */
    NSTimer *_timer;/**< 定时器 */
    double _changeVideoType_Time;/**< 记录同一课程的音、视频切换的时间，不同课程的切换回变成0 */
    NSString *_UUID;/**< 记录课程的UUID */
    NSString *_studetailcount;/**< 随currentID变化，当currentID发生变化的第一次提交数据时为0，数据成功后变成1，后面一直是1，直到该门课程播放完成或者发生切课。 */
    BOOL _isPlayVideo;/**< 是否播放视频，yes 视频  no 音频 */
}
/** 播放视图 */
@property (nonatomic, strong) UIView *playView;
/** 课程名称及课程评分收藏情况 */
@property (nonatomic, strong) ZJCourseNameView *courseNameView;
/** 选集 */
@property (nonatomic, strong) ZJCourseSelectionsView *courseSelectionsView;
/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/** 课程简介 */
@property (nonatomic, strong) ZJCourseIntroView *courseIntroView;
/** 师资 */
@property (nonatomic, strong) ZJCourseTeacherView *courseTeacherView;

/** 下方收藏及评价按钮 */
@property (nonatomic, strong) ZJCourseCommentAndCollectView *commentAndCollectView;
/** 保利威视的播放器 */
//@property (nonatomic, strong) PLVVodSkinPlayerController *player;
/** 自己的播放器播放器 */
@property (nonatomic, strong) KYVedioPlayer *player1;
/**< 记录最后播放时间 (视频切换) */
@property (nonatomic, assign) NSTimeInterval laststudytime;
/** 评论模块 */
@property (nonatomic, strong) YBCommentVideoView *commentVideoView;
@end

@implementation ZJVidoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.classId.length == 0) {
        self.classId = @"";
    }
    self.titlelabel.text = @"详情";
    [self getChangePropsFromChangeCourse];
    _isComment = NO;
    [self setupUI];
    [self initData];

}

- (void)setVideoBackPlay{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    if (_isPlayVideo) {
        [session setCategory:AVAudioSessionCategorySoloAmbient error:nil];
    }else{//音频
         //支持后台播放
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    }
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.player1.isPlaying) {
        [self.player1 pause];
    }
     [_timer invalidate];
    [self netWorking_video_begin];

    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    //清楚后台播放标记
    [ToolClass setBackPlayInfoWithTitle:@"" singer:@"" imageName:@"" totalTime:0 alreadyTime:0];
}

- (void)setupUI{
    [self.view addSubview:self.playView];
    [self.view addSubview:self.courseNameView];
    [self.view addSubview:self.courseSelectionsView];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.courseIntroView];
    [self.scrollView addSubview:self.courseTeacherView];
    [self.view addSubview:self.commentAndCollectView];
    
    self.playView.sd_layout
    .topSpaceToView(self.navigView, 0)
    .leftEqualToView(self.navigView)
    .widthIs(self.view.width)
    .heightIs(self.view.width / 16 * 9);
    
    self.courseNameView.sd_layout
    .topSpaceToView(self.playView, 0)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0);
    
    self.courseSelectionsView.sd_layout
    .topSpaceToView(self.courseNameView, 0)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0);
    
    self.commentAndCollectView.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view)
    .heightIs(50 * [UIScreen zj_screenHScale]);
    
    self.scrollView.sd_layout
    .topSpaceToView(self.courseSelectionsView, 0)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0)
    .bottomSpaceToView(self.commentAndCollectView, 0);
    
    self.courseIntroView.sd_layout
    .topSpaceToView(self.scrollView, 0)
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0);
    
    self.courseTeacherView.sd_layout
    .topSpaceToView(self.courseIntroView, 5 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.courseIntroView)
    .rightEqualToView(self.courseIntroView);
    
    [self.scrollView setupAutoContentSizeWithBottomView:self.courseTeacherView bottomMargin:0];
    
}
#pragma mark - 初始化数据
- (void)initData{
    [self getCourseInfo];
    [self getCourseTeacherInfo];
}
#pragma mark - 初始化数据接口
///课程基本信息
- (void)getCourseInfo{
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    [ZJRequestManager request_getCoursewareInfoWithID:self.model.ID successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSArray *array = [object objectForKey:@"data"];
            if (array.count > 0) {
                self.model = [LPZWYChooseClassClassModel yy_modelWithJSON:array.firstObject];
                [weakSelf initUIFromNetWorkingData];
                self.ybTitleString = self.model.name.length > 0 ? self.model.name : @"详情";
                [YJProgressHUD zj_MainThead_hide];
            }else{
                [weakSelf netWroking_Error_PopVC];
            }
        }else{
           [weakSelf netWroking_Error_PopVC];
        }
    } failBlock:^(id object) {
        [weakSelf netWroking_Error_PopVC];
    }];
}
///初始化接口请求失败就返回上个界面
- (void)netWroking_Error_PopVC{
    [YJProgressHUD zj_MainThead_showMessage:@"网络请求失败" inView:self.view];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[ToolClass getMainNavigationController] popViewControllerAnimated:YES];
    });
}

///师资信息
- (void)getCourseTeacherInfo{
    __weak typeof(self) weakSelf = self;
    [ZJRequestManager request_getCoursewareTeacherInfoWithID:self.model.ID successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSArray *array = [object objectForKey:@"data"];
            ZJCourseTeacherModel *model = [ZJCourseTeacherModel yy_modelWithJSON:array.firstObject];
            weakSelf.courseTeacherView.model = model;
        }
    } failBlock:^(id object) {
        
    }];
}

#pragma mark - 判断是否加入待学，（未加入待学时，点击播放要加入待学）
///判断是否加入待学
- (void)isAddAwaitStudy{
    //是否是待学的课程:0表示不是待学课程,1有值的表示是待学课程
    if ([self.model.ifwaitcourse integerValue] == 0) {//未加入待学
        [self addAwaitStudy_netWorking];
    }
}
///加入待学的网络请求
- (void)addAwaitStudy_netWorking{
    [ZJRequestManager request_getCourseAddAwaitStudyWithCoursewareid:self.model.ID successBlock:^(id object) {
        
    } failBlock:^(id object) {
        
    }];
}

#pragma mark - 根据网络请求的数局来初始化界面
- (void)initUIFromNetWorkingData{
    [self initPlayVideoController1];
    self.courseNameView.model = self.model;
    ///收藏
    if ([self.model.ifcollectedcourse integerValue] == 0) {
        [self.commentAndCollectView setCollectButtonIsCollect:NO];
    }else{
        [self.commentAndCollectView setCollectButtonIsCollect:YES];
    }
    ///评价
    //已评1，未评0
    if ([self.model.isappraised integerValue] == 0) {
        _isComment = NO;
    }else{
        _isComment = YES;
    }
    [self.commentAndCollectView setCommentButtonIsComment:_isComment model:self.model];
    ///课程简介
    [self.courseIntroView setContentLabelText:self.model.comment];
    ///判断选集模块的显示与隐藏
    
    NSArray *selesArray = self.model.suitejson ? [self jsonStringToObject:self.model.suitejson] :@[];
    if (selesArray.count > 1) {//选集显示
        NSArray *selesModelArray = [NSArray yy_modelArrayWithClass:[ZJSelectionsMdel class] json:selesArray];
        
        self.courseSelectionsView.hidden = NO;
        [self.courseSelectionsView setCourseID:self.model.ID];
        [self.courseSelectionsView setDataArray:selesModelArray];
        self.scrollView.sd_layout
        .topSpaceToView(self.courseSelectionsView, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.commentAndCollectView, 0);
    }else{//选集隐藏
        self.courseSelectionsView.hidden = YES;
        self.scrollView.sd_layout
        .topSpaceToView(self.courseNameView, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.commentAndCollectView, 0);
    }
    [self.scrollView updateLayout];
}

#pragma mark - 初始化控制器
//- (void)initPlayVideoController{
//    if (!self.player) {
//        self.player = [[PLVVodSkinPlayerController alloc] initWithNibName:nil bundle:nil];
//        self.player.autoplay = NO;//是否自动播放
//        self.player.enableTeaser = YES;
////        self.player.rememberLastPosition = YES;
//        self.player.enableBackgroundPlayback = YES;// 是否允许后台播放
//
//        self.player.videoCoverView.delegate = self;
//        [self.player addPlayerOnPlaceholderView:self.playView rootViewController:self];
//    }
//
//    [self.player.videoCoverView setBgImageViewURL:self.model.imagephoto timeString:self.model.realduration];
//    NSString *videoID = @"";
//    if ([self getPayerTypeIsVideoOrVoice]) {//视频
//        videoID = self.model.teachervideo;
//        [self.courseNameView setVideoPlayType_isVideo:YES];
//    }else{
//        videoID = self.model.audio_url;
//        [self.courseNameView setVideoPlayType_isVideo:NO];
//    }
//     __weak typeof(self) weakSelf = self;
//    [PLVVodVideo requestVideoWithVid:videoID completion:^(PLVVodVideo *video, NSError *error) {
//        [weakSelf.player setVideo:video];
//        ///设置播放开始时间
//        [weakSelf.player setStartPlaybackTime:[self.model.lastplaytime doubleValue] + 1];
//        [weakSelf netWorking_video_begin];
//    }];
//    ///监听播放器的状态
//    [self.player setPlaybackStateHandler:^(PLVVodPlayerViewController *player) {
//        if (weakSelf.player.playbackState == PLVVodPlaybackStatePlaying || weakSelf.player.playbackState == PLVVodPlaybackStatePaused) {//播放
//            [ToolClass setBackPlayInfoWithTitle:[NSString string:weakSelf.model.name isNilStringReturnDeftString:@"暂无" ]
//                                         singer:[NSString string:weakSelf.model.teachersname isNilStringReturnDeftString:@"暂无" ]
//                                      imageName:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,weakSelf.model.imagephoto]
//                                      totalTime:0
//                                    alreadyTime:0];
//        }
//    }];
//    ///播放结束
//    [self.player setReachEndHandler:^(PLVVodPlayerViewController *player) {
//        [weakSelf netWorking_video_begin];
//        [weakSelf stopTimer];
//    }];
//
//}

- (void)initPlayVideoController1{
    [self releasePlayer];
    if (!self.player1) {
        CGRect playerFrame = CGRectMake(0, 0, self.playView.width, self.playView.height);
        self.player1 = [[KYVedioPlayer alloc]initWithFrame:playerFrame];
        self.player1.delegate = self;
        self.player1.videoCoverView.delegate = self;
        self.player1.closeBtn.hidden = YES;
        self.player1.progressColor = [UIColor whiteColor];
        [self.playView addSubview:self.player1];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NotificationDeviceOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    
    [self.player1.videoCoverView setBgImageViewURL:self.model.imagephoto timeString:self.model.realduration];
    NSString *URLString = @"";
    if ([self getPayerTypeIsVideoOrVoice]) {//视频
        if (self.model.teachervideo.length > 0) {
            URLString = self.model.teachervideo;
        }
        [self.courseNameView setVideoPlayType_isVideo:YES];
    }else{
        if (self.model.audio_url.length > 0) {
            URLString = self.model.audio_url;
        }
        [self.courseNameView setVideoPlayType_isVideo:NO];
    }
    self.player1.URLString = URLString;
//    self.player1.URLString = @"http://hjq-1257036536.cos.ap-shanghai.myqcloud.com/m3u8/m1/video.m3u8";
}
/**
 *  注销播放器
 **/
- (void)releasePlayer
{
    [self.player1 resetKYVedioPlayer];
    self.player1 = nil;
}

#pragma mark - 视屏播放相关接口
///开始
- (void)netWorking_video_begin{
    __weak typeof(self) weakSelf = self;
    [ZJRequestManager request_getCoursePlayerBeginWithCoursewareid:self.model.ID courwarestudytime:self.model.studytime successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSDictionary *dict = [object objectForKey:@"data"];
            NSString *pkey = [dict objectForKey:@"pkey"];
            if (pkey.length > 0) {
                [weakSelf netWorking_video_SaveSchedule_pkey:pkey];
            }
        }
    } failBlock:^(id object) {
        
    }];
}

///保存进度
- (void)netWorking_video_SaveSchedule_pkey:(NSString *)pkey{
    [ZJRequestManager request_getCoursePlayerSaveScheduleWithCoursewareid:self.model.ID
                                                                     time:[NSString stringWithFormat:@"%f",self.player1.currentPlaybackTime]
                                                                     pkey:pkey
                                                            videoDuration:self.model.realduration
                                                        courwarestudytime:self.model.studytime
                                                               playerTime:[NSString stringWithFormat:@"%.0f",self.player1.viewerWatchDuration + _changeVideoType_Time]
                                                           coursewarename:self.model.name
                                                                currentID:_UUID
                                                           studetailcount:_studetailcount
                                                                  classId:self.classId
                                                             successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {//请求成功
            if ([_studetailcount isEqualToString:@"0"]) {
                _studetailcount = @"1";
            }
         }
                    
    } failBlock:^(id object) {
        
    }];
}

#pragma mark - NSTimer
- (void)initTimer{
    dispatch_async(dispatch_get_main_queue(), ^{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(netWorking_video_begin) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        
    }else{
        [self startTimer];
    }
    });
}
///开始timer
- (void)startTimer{
    dispatch_async(dispatch_get_main_queue(), ^{
    _timer.fireDate = [NSDate distantPast];
    });
}
///暂停timer
- (void)stopTimer{
    dispatch_async(dispatch_get_main_queue(), ^{
    _timer.fireDate = [NSDate distantFuture];
    });
}

- (void)dealloc{
    _timer = nil;
    [self releasePlayer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - ZJVideoCoverViewDelegate(点击播放) 协议方法
///点击播放
- (void)ZJVideoCoverViewDelegate_player{
    if ([self getPayerTypeIsVideoOrVoice]) {//视频
        self.player1.videoCoverView.hidden = YES;
        _isPlayVideo = YES;
    }else{
        _isPlayVideo = NO;
        self.player1.videoCoverView.hidden = NO;
        [self.player1.videoCoverView hiddenViews];
    }
    [self setVideoBackPlay];
    [self.player1 setVideoCoverViewToBack];
    //加入待学
    [self isAddAwaitStudy];
    if ([self.model.lastplaytime doubleValue] > 1) {
        [self alertTime];
    }else{
        [self initTimer];
        [self.player1 play];
        [self.player1 setStartPlaybackTime:[self.model.lastplaytime doubleValue] + 1];
    }
  }

- (void)alertTime{
    NSString *timeString = [NSString stringWithFormat:@"是否从上次学习位置%@开始播放？",[NSString getTimeLabelValues:[self.model.lastplaytime doubleValue] + 1]];
    __weak typeof(self) weakSelf = self;
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:timeString  preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initTimer];
        [weakSelf.player1 play];
        [weakSelf.player1 setStartPlaybackTime:0];
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initTimer];
        [weakSelf.player1 play];
        [weakSelf.player1 setStartPlaybackTime:[self.model.lastplaytime doubleValue] + 1];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - ZJCourseNameViewDelegate(视频和音频的切换) 协议方法
- (void)ZJCourseNameViewDelegate_isSwithVideo:(BOOL)isSwithVideo{
    ///记录当前时间
    self.laststudytime = ceil(self.player1.currentPlaybackTime) ;
    _changeVideoType_Time = self.player1.viewerWatchDuration + _changeVideoType_Time;
    if (isSwithVideo) {//播放视频
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:YBUSERINFOMODEL.sessionId];//记录偏好
    }else{//播放音频
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:YBUSERINFOMODEL.sessionId];//记录偏好
    }
    [self initPlayVideoController1];
    if (isSwithVideo) {//播放视频
        _isPlayVideo = YES;
        self.player1.videoCoverView.hidden = YES;
    }else{//播放音频
        _isPlayVideo = NO;
        self.player1.videoCoverView.hidden = NO;
        [self.player1.videoCoverView hiddenViews];
    }
    [self.player1 setVideoCoverViewToBack];
    [self.player1 play];
    [self setVideoBackPlay];
    [self.player1 setStartPlaybackTime:self.laststudytime];
    
    return;
   
}
#pragma mark - ZJCourseSelectionsViewDelegate(选集) 协议方法
- (void)ZJCourseSelectionsViewDelegate_buttonClick_CourseID:(NSString *)courseID{
    [self.player1 pause];
    [self.player1 clearVideoviewerWatchDuration];//清除统计
    self.model.ID = courseID;
    [self getChangePropsFromChangeCourse];
    [self initData];
}
#pragma mark - ZJCourseCommentAndCollectViewDelegate(下方收藏和评论按钮) 协议方法
///取消收藏

- (void)ZJCourseCommentAndCollectViewDelegate_cancelCollect{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    NSArray *array = [self getCourseIdArray];
    [ZJRequestManager request_getCoursewareCancelCollectWithCoursewareIdArray:array successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSDictionary *dict = [object objectForKey:@"data"];
            if ([[dict objectForKey:@"result"] integerValue] == 1) {//取消收藏成功
                [YJProgressHUD zj_MainThead_showMessage:@"取消收藏成功" inView:weakSelf.view];
                [weakSelf.commentAndCollectView setCollectButtonIsCollect:NO];
                return ;
            }
        }
        [YJProgressHUD zj_MainThead_showMessage:@"取消收藏失败" inView:weakSelf.view];
    } failBlock:^(id object) {
         [YJProgressHUD zj_MainThead_showMessage:@"取消收藏失败" inView:weakSelf.view];
    }];
}
///收藏
- (void)ZJCourseCommentAndCollectViewDelegate_collect{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    NSArray *array = [self getCourseIdArray];
    [ZJRequestManager request_getCoursewareCollectWithCoursewareIdArray:array successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSDictionary *dict = [object objectForKey:@"data"];
            if ([[dict objectForKey:@"result"] integerValue] == 1) {//收藏成功
                [YJProgressHUD zj_MainThead_showMessage:@"收藏成功" inView:weakSelf.view];
                [weakSelf.commentAndCollectView setCollectButtonIsCollect:YES];
                return ;
            }
        }
        [YJProgressHUD zj_MainThead_showMessage:@"收藏失败" inView:weakSelf.view];
    } failBlock:^(id object) {
        [YJProgressHUD zj_MainThead_showMessage:@"收藏失败" inView:weakSelf.view];
    }];
}

- (NSArray *)getCourseIdArray{
    if (!self.model.suitejson) {
        return @[self.model.ID];
    }
    NSArray *models =  [NSArray yy_modelArrayWithClass:[ZJSelectionsMdel class] json:[self jsonStringToObject:self.model.suitejson]] ;
    if (models.count == 0) {
        return @[];
    }
    __block NSMutableArray *array = [NSMutableArray array];
    [models enumerateObjectsUsingBlock:^(ZJSelectionsMdel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [array addObject:obj.coursewareid];
    }];
    return array;
}

///评论
- (void)ZJCourseCommentAndCollectViewDelegate_comment{
    [self.view addSubview:self.commentVideoView];
}

#pragma mark - YBCommentVideoViewDelegate(评论视图的回调) 协议方法
- (void)ybCommentVideoView:(YBCommentVideoView *)ybCommentVideoView didClickCommitButtonWithDataArray:(NSArray *)dataArray nameArray:(NSArray *)nameArray{
    if ([dataArray containsObject:@"0"]) {//未评价完
        [YJProgressHUD zj_MainThead_showMessage:@"请完整评分" inView:self.view];
        return;
    }
    [ybCommentVideoView removeFromSuperview];
    
    __block NSMutableArray *array = [NSMutableArray array];
    
    [nameArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[NSString stringWithFormat:@"%ld",idx + 1] forKey:@"itemid"];
        [dict setObject:obj forKeyedSubscript:@"itemname"];
        [dict setObject:dataArray[idx] forKeyedSubscript:@"rate"];
        [dict setObject:[NSString stringWithFormat:@"%ld",dataArray.count] forKeyedSubscript:@"max"];
        [dict setObject:@"0" forKeyedSubscript:@"isReadonly"];
        [dict setObject:@"" forKeyedSubscript:@"overStar"];
        [dict setObject:[NSString stringWithFormat:@"%ld",[dataArray[idx] integerValue] * 2] forKeyedSubscript:@"percent"];
        [array addObject:dict];
    }];
    [self comment_NetWroking_dataArray:array];
}
///评分的网络请求
- (void)comment_NetWroking_dataArray:(NSArray *)array{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    [YBRequestManager request_ybCommitClassWithClasscourseid:@"" coursewareid:self.model.ID classid:@"" scoreList:array successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            [YJProgressHUD zj_MainThead_showMessage:@"评分成功" inView:weakSelf.view];
            [weakSelf.commentAndCollectView setCommentButtonIsComment:YES model:weakSelf.model];
            return ;
        }
        [YJProgressHUD zj_MainThead_showMessage:@"评分失败" inView:weakSelf.view];
    } failBlock:^(id object) {
        [YJProgressHUD zj_MainThead_showMessage:@"评分失败" inView:weakSelf.view];
    }];
}

#pragma mark - 后台播放控制
-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type==UIEventTypeRemoteControl) {
        if (event.subtype==UIEventSubtypeRemoteControlPlay) {
            //播放
            [self.player1 play];
        }
        if (event.subtype==UIEventSubtypeRemoteControlPause) {
            //暂停
            [self.player1 pause];
        }
    }
}

#pragma mark - 判断课程优先 播放视频还是音频
///判断这个课程优先播放视频还是音频  yes是视频  NO是音频
- (BOOL)getPayerTypeIsVideoOrVoice{
    if ([VIDEO_TYPE isEqualToString:@"1"]) {//优先播放音频
        if (self.model.audio_url) {
            return NO;
        }else{
            return YES;
        }
    }else{//优先播放视频
        if (self.model.teachervideo) {
            return YES;
        }else{
            return NO;
        }
    }
}
#pragma mark - 切换课程需要改变的值
- (void)getChangePropsFromChangeCourse{
    _changeVideoType_Time = 0.0;
    _UUID = [ToolClass createUUIDString];
    _studetailcount = @"0";
}

#pragma mark - 自定义播放器的 屏幕旋转
-(void)NotificationDeviceOrientationChange:(NSNotification *)notification{
    if (self.player1 == nil|| self.player1.superview==nil || !self.player1.videoCoverView.hidden){
        return;
    }
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortraitUpsideDown:{
//            NSLog(@"第3个旋转方向---电池栏在下");
            [UIApplication sharedApplication].statusBarHidden = YES;
        }
            break;
        case UIInterfaceOrientationPortrait:{
//            NSLog(@"第0个旋转方向---电池栏在上");
            [UIApplication sharedApplication].statusBarHidden = NO;
            if (self.player1.isFullscreen) {
//                [self setNeedsStatusBarAppearanceUpdate];
                [self.player1 showSmallScreenWithPlayer:self.player1 withFatherView:self.view withFrame:self.playView.frame];
            }
        }
            break;
        case UIInterfaceOrientationLandscapeLeft:{
//            NSLog(@"第2个旋转方向---电池栏在左");
            self.player1.isFullscreen = YES;
//            [self setNeedsStatusBarAppearanceUpdate];
            [UIApplication sharedApplication].statusBarHidden = YES;
            [self.player1 showFullScreenWithInterfaceOrientation:interfaceOrientation player:self.player1 withFatherView:self.view];
        }
            break;
        case UIInterfaceOrientationLandscapeRight:{
//            NSLog(@"第1个旋转方向---电池栏在右");
            self.player1.isFullscreen = YES;
//            [self setNeedsStatusBarAppearanceUpdate];
            [UIApplication sharedApplication].statusBarHidden = YES;
            [self.player1 showFullScreenWithInterfaceOrientation:interfaceOrientation player:self.player1 withFatherView:self.view];
        }
            break;
        default:
            break;
    }
}
#pragma mark - 自定义播放器的 协议方法
//点击全屏按钮代理方法
-(void)kyvedioPlayer:(KYVedioPlayer *)kyvedioPlayer clickedFullScreenButton:(UIButton *)fullScreenBtn{
    if (!self.player1.videoCoverView.hidden) {
        return;
    }
    if (fullScreenBtn.selected) {
        self.player1.isFullscreen = YES;
//        [self setNeedsStatusBarAppearanceUpdate];
        [UIApplication sharedApplication].statusBarHidden = YES;
        [self.player1 showFullScreenWithInterfaceOrientation:UIInterfaceOrientationLandscapeLeft player:self.player1 withFatherView:self.view];
    }else{
//        [self setNeedsStatusBarAppearanceUpdate];
        [UIApplication sharedApplication].statusBarHidden = NO;
        [self.player1 showSmallScreenWithPlayer:self.player1 withFatherView:self.view withFrame:self.playView.frame];
    }
}
//点击播放暂停按钮代理方法
-(void)kyvedioPlayer:(KYVedioPlayer *)kyvedioPlayer clickedPlayOrPauseButton:(UIButton *)playOrPauseBtn{
    if (!playOrPauseBtn.isSelected) {//播放
        [self initTimer];
        [ToolClass setBackPlayInfoWithTitle:[NSString string:self.model.name isNilStringReturnDeftString:@"暂无" ]
                                     singer:[NSString string:self.model.teachersname isNilStringReturnDeftString:@"暂无" ]
                                  imageName:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,self.model.imagephoto]
                                  totalTime:0
                                alreadyTime:0];
    }else{//暂停
        [self stopTimer];
    }
}
//播放完毕的代理方法
-(void)kyplayerFinishedPlay:(KYVedioPlayer *)kyvedioPlayer{
    [self stopTimer];
}

#pragma mark - Setter


#pragma mark - Getters
- (UIView *)playView{
    if (_playView == nil){
        _playView = [UIView new];
    }
    return _playView;
}

- (ZJCourseNameView *)courseNameView{
    if (_courseNameView == nil){
        _courseNameView = [ZJCourseNameView new];
        _courseNameView.delegate = self;
    }
    return _courseNameView;
}

- (ZJCourseIntroView *)courseIntroView{
    if (_courseIntroView == nil){
        _courseIntroView = [[ZJCourseIntroView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 10) title:@"课程简介"];
        
    }
    return _courseIntroView;
}
- (ZJCourseTeacherView *)courseTeacherView{
    if (_courseTeacherView == nil){
        _courseTeacherView = [[ZJCourseTeacherView alloc] init_title:@"主讲人"];
        
    }
    return _courseTeacherView;
}
- (UIScrollView *)scrollView{
    if (_scrollView == nil){
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.contentOffset = CGPointZero;
        _scrollView.backgroundColor = [UIColor zj_colorWithHexString:@"f0f0f0"];
    }
    return _scrollView;
}
- (ZJCourseCommentAndCollectView *)commentAndCollectView{
    if (_commentAndCollectView == nil){
        _commentAndCollectView = [ZJCourseCommentAndCollectView new];
        _commentAndCollectView.delelgate = self;
    }
    return _commentAndCollectView;
}
- (ZJCourseSelectionsView *)courseSelectionsView{
    if (_courseSelectionsView == nil){
        _courseSelectionsView = [[ZJCourseSelectionsView alloc] init];
        _courseSelectionsView.delelgate = self;
    }
    return _courseSelectionsView;
}

- (YBCommentVideoView *)commentVideoView{
    if (_commentVideoView == nil){
        _commentVideoView = [[YBCommentVideoView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) titleArray:@[@"观点正确",@"表达流畅",@"内容丰富",@"授课认真",@"形象生动"]];
        _commentVideoView.delegate = self;
    }
    return _commentVideoView;
}

@end
